package com.lw.smartdevice.events.listeners;

import com.lw.smartdevice.enums.LoginResultEnum;
import com.lw.smartdevice.events.MyLoginEvent;
import com.lw.smartdevice.mapper.SysLogininforMapper;
import com.lw.smartdevice.mapper.SysUserOnlineMapper;
import com.lw.smartdevice.pojo.SysLogininfor;
import com.lw.smartdevice.pojo.SysUserOnline;
import com.lw.smartdevice.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/20 15:55
 */
@Component
//@EnableAsync//开启异步支持,  @Async才会有效,这个注解只需要写一次
public class LoginEventListener {

    private SysLogininforMapper sysLogininforMapper;

    private SysUserOnlineMapper sysUserOnlineMapper;

    @Autowired
    public void setSysUserOnlineMapper(SysUserOnlineMapper sysUserOnlineMapper) {
        this.sysUserOnlineMapper = sysUserOnlineMapper;
    }

    @Autowired
    public void setSysLogininforMapper(SysLogininforMapper sysLogininforMapper) {
        this.sysLogininforMapper = sysLogininforMapper;
    }

    private Logger logger = LoggerFactory.getLogger(LoginEventListener.class);

    @EventListener
    //@Async//异步执行
    public void onEvent(MyLoginEvent event){
        logger.error("收到登录操作的事件了");
        //获取请求对象
        //因为是通过trreadlocal获取到的，所以拿的时候不能放到异步
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        CompletableFuture.runAsync(()->{
            HttpServletRequest request = requestAttributes.getRequest();
            String sessionId = request.getSession().getId();//获取sessionId
            String ip = RequestUtil.getRemoteHost(request);//获取到ip
            Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//获取到操作系统和浏览器信息
            String locationByIp = RequestUtil.getLocationByIp(ip);//获取到ip对应的地区
            //保存数据到对象中
            SysLogininfor sysLogininfor=new SysLogininfor();
            sysLogininfor.setIpaddr(ip);
            sysLogininfor.setLoginLocation(locationByIp);
            sysLogininfor.setLoginName(event.getUserName());
            sysLogininfor.setLoginTime(new Date());
            sysLogininfor.setBrowser(osAndBrowserInfo.get("browser"));
            sysLogininfor.setOs(osAndBrowserInfo.get("os"));
            switch (event.getLoginResultEnum()){
                case SUCCESS:
                    sysLogininfor.setMsg("登录成功");
                    sysLogininfor.setStatus("1");
                    break;

                case FAIL:
                    sysLogininfor.setMsg("登录失败");
                    sysLogininfor.setStatus("0");
                    break;
            }
            System.err.println(sysLogininfor);
            //保存到数据库
            sysLogininforMapper.addLoginLog(sysLogininfor);

            if(event.getLoginResultEnum()== LoginResultEnum.SUCCESS){
                //登录成功之后需要更新在线用户
                //根据request获取sessionId

                SysUserOnline sysUserOnline = new SysUserOnline();
                BeanUtils.copyProperties(sysLogininfor,sysUserOnline);
                sysUserOnline.setSessionId(sessionId);
                sysUserOnline.setExpireTime(30L);
                sysUserOnline.setStartTimestamp(new Date());
                logger.error("在线用户对象:"+sysUserOnline);
                int count = sysUserOnlineMapper.findByUserName(sysLogininfor.getLoginName());
                if (count == 1) {
                    //更新数据
                    sysUserOnlineMapper.updateSysUserOnline(sysUserOnline);
                }else{
                    //添加数据
                    sysUserOnlineMapper.addSysUserOnline(sysUserOnline);
                }

            }
        });

    }
}
